<!-- 页面 -->
<template>
  <s-layout title="理财明细">
    <s-empty
      v-if="state.pagination.total === 0"
      icon="/static/order-empty.png"
      :text="t('pages.user.order.zanwu')"
    ></s-empty>
    <view v-if="state.pagination.total > 0">
      <view
        class="list-item ss-flex ss-col-center ss-row-between"
        v-for="item in state.pagination.data"
        :key="item.id"
      >
        <view class="ss-flex-col">
          <view class="name">{{ item.memo }}</view>
          <view class="time">{{ item.createtime }}</view>
        </view>
        <view>
			<view class="add" v-if="item.amount > 0">+{{ item.amount }}</view>
			<view class="minus" v-else>{{ item.amount}}</view>
			<view class="time">本金：{{ item.principal}}</view>
		</view>
      </view>
    </view>

    <!-- 加载更多 -->
    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown:$t('pages.user.wallet.load'),
      }"
      @tap="loadmore"
    />
  </s-layout>
</template>

<script setup>
  import { computed, reactive } from 'vue';
  import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
  import { formatOrderColor } from '@/sheep/hooks/useGoods';
  import sheep from '@/sheep';
  import _ from 'lodash';
  import { isEmpty } from 'lodash';
import { useI18n } from 'vue-i18n'
	const { t }  = useI18n()
  const tradeManaged = computed(() => sheep.$store('app').has_wechat_trade_managed);

  const pagination = {
    data: [],
    current_page: 1,
    total: 1,
    last_page: 1,
  };
  // 数据
  const state = reactive({
    ids: '',
    currentTab: 0,
    pagination: {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
    },
    loadStatus: '',
    deleteOrderId: 0,
    error: 0,
  });

  const tabMaps = [
    {
      name: t('pages.user.orderMap.allOrders'),
      value: 'all',
    },
    {
      name: t('pages.user.orderMap.pending'),
      value: 'unpaid',
    },
    {
      name: t('pages.user.order.daifahuo'),
      value: 'nosend',
    },
    {
      name: t('pages.user.orderMap.received'),
      value: 'noget',
    },
    {
      name: t('pages.user.orderMap.evaluated'),
      value: 'nocomment',
    },
  ];

  // 切换选项卡
  function onTabsChange(e) {
    if (state.currentTab === e.index) return;

    state.pagination = pagination;

    state.currentTab = e.index;

    getOrderList();
  }

  // 订单详情
  function onOrderDetail(id) {
   //  sheep.$router.go('/pages/financial/details', {
   //    id,
	  // order: 1
   //  });
  }

  // 分享拼团
  function onOrderGroupon(order) {
    sheep.$router.go('/pages/activity/groupon/detail', {
      id: order.ext.groupon_id,
    });
  }

  // 查看发票
  function onOrderInvoice(invoiceId) {
    sheep.$router.go('/pages/order/invoice', {
      invoiceId,
    });
  }

  // 继续支付
  function onPay(orderSN) {
    sheep.$router.go('/pages/pay/index', {
      orderSN,
    });
  }

  // 评价
  function onComment(orderSN) {
    sheep.$router.go('/pages/goods/comment/add', {
      orderSN,
    });
  }

  // 确认收货
  async function onConfirm(order, ignore = false) {
    // 需开启确认收货组件
    // todo:
    // 1.怎么检测是否开启了发货组件功能？如果没有开启的话就不能在这里return出去
    // 2.如果开启了走mpConfirm方法,需要在App.vue的show方法中拿到确认收货结果
    if (
      sheep.$platform.name === 'WechatMiniProgram' &&
      !isEmpty(order.wechat_extra_data) &&
      tradeManaged.value === 1 &&
      !ignore
    ) {
      mpConfirm(order);
      return;
    }

    // 正常的确认收货流程
    const { code, data } = await sheep.$api.order.confirm(order.id);
    if (code === 1) {
      // let index = state.pagination.data.findIndex((order) => order.id === orderId);
      // state.pagination.data[index] = data;
      state.pagination = pagination;
      getOrderList();
    }
  }

  // #ifdef MP-WEIXIN
  // 小程序确认收货组件
  function mpConfirm(order) {
    if (!wx.openBusinessView) {
      sheep.$helper.toast(`请升级微信版本`);
      return;
    }
    wx.openBusinessView({
      businessType: 'weappOrderConfirm',
      extraData: {
        merchant_trade_no: order.wechat_extra_data.merchant_trade_no,
        transaction_id: order.wechat_extra_data.transaction_id,
      },
      success(response) {
        console.log('success:', response);
        if (response.errMsg === 'openBusinessView:ok') {
          if (response.extraData.status === 'success') {
            onConfirm(order, true);
          }
        }
      },
      fail(error) {
        console.log('error:', error);
      },
      complete(result) {
        console.log('result:', result);
      },
    });
  }
  // #endif

  // 查看物流
  async function onExpress(orderId) {
    sheep.$router.go('/pages/order/express/list', {
      orderId,
    });
  }

  // 取消订单
  async function onCancel(orderId) {
    uni.showModal({
      title: t('pages.goods.order.tishi'),
      content: t('pages.user.order.quxiaoorder')+'?',
      success: async function (res) {
        if (res.confirm) {
          const { code, data } = await sheep.$api.order.cancel(orderId);
          if (code === 1) {
            let index = state.pagination.data.findIndex((order) => order.id === orderId);
            state.pagination.data[index] = data;
          }
        }
      },
    });
  }

  // 删除订单
  function onDelete(orderId) {
    uni.showModal({
      title: t('pages.goods.order.tishi'),
      content: t('pages.user.order.delorder')+'?',
      success: async function (res) {
        if (res.confirm) {
          const { code, data } = await sheep.$api.order.delete(orderId);
          if (code === 1) {
            let index = state.pagination.data.findIndex((order) => order.id === orderId);
            state.pagination.data.splice(index, 1);
          }
        }
      },
    });
  }

  // 申请退款
  async function onRefund(orderId) {
    uni.showModal({
      title: '提示',
      content: '确定要申请退款吗?',
      success: async function (res) {
        if (res.confirm) {
          // #ifdef MP
          sheep.$platform.useProvider('wechat').subscribeMessage('order_refund');
          // #endif
          const { code, data } = await sheep.$api.order.applyRefund(orderId);
          if (code === 1) {
            let index = state.pagination.data.findIndex((order) => order.id === orderId);
            state.pagination.data[index] = data;
          }
        }
      },
    });
  }

  // 获取订单列表
  async function getOrderList(page = 1, list_rows = 5) {
    state.loadStatus = 'loading';
    let res = await sheep.$api.financial.user_financial_log(state.ids);
    state.error = res.error;
    if (res.code === 1) {
      let orderList = _.concat(state.pagination.data, res.data.data);
      state.pagination = {
        ...res.data,
        data: orderList,
      };
      if (state.pagination.current_page < state.pagination.last_page) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    }
  }

  onLoad(async (options) => {
    if (options.id) {
      state.ids = options.id;
    }
    getOrderList();
  });

  // 加载更多
  function loadmore() {
    if (state.loadStatus !== 'noMore') {
      getOrderList(state.pagination.current_page + 1);
    }
  }

  // 上拉加载更多
  onReachBottom(() => {
    loadmore();
  });

  //下拉刷新
  onPullDownRefresh(() => {
    state.pagination = pagination;
    getOrderList();
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 800);
  });
</script>

<style lang="scss" scoped>
	.botton {
		font-size: 30rpx;
		background-color: #cf3835;
		color: #fff;
		padding: 5rpx 20rpx;
		border-radius: 10rpx;
		text-align: center;
		margin-top: 30rpx;
	}
	.card-left {
		
		.top {
			color: #cf3835;
			font-size: 35rpx;
			font-weight: 500;
		}
		.bottom {
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
	}
	.card-center {
		text-align: center;
		
		.top {
			color: #333;
			font-size: 30rpx;
			font-weight: 500;
		}
		.bottom {
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
	}
	.card-bottom {
		width: 100%;
		margin-top: 20rpx;
		
		.bottom {
			font-size: 24rpx;
			color: #999;
		}
	}
	.card-right {
		
		
		.top {
			color: #cf3835;
			font-size: 24rpx;
			font-weight: 500;
		}
		.bottom {
			font-size: 30rpx;
			background-color: #cf3835;
			color: #fff;
			padding: 5rpx 20rpx;
			border-radius: 10rpx;
			text-align: center;
			margin-top: 10rpx;
		}
	}
  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .tool-btn {
    // width: 160rpx;
	padding: 0 10rpx;
    height: 60rpx;
    background: #f6f6f6;
    font-size: 26rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;

    &:last-of-type {
      margin-right: 0;
    }
  }
  .delete-btn {
    // width: 160rpx;
    padding: 0 10rpx;
    height: 56rpx;
    color: #ff3000;
    background: #fee;
    border-radius: 28rpx;
    font-size: 26rpx;
    margin-right: 10rpx;
    line-height: normal;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .apply-btn {
    // width: 160rpx;
    padding: 0 10rpx;
    height: 50rpx;
    border-radius: 25rpx;
    font-size: 24rpx;
    border: 2rpx solid #dcdcdc;
    line-height: normal;
    margin-left: 16rpx;
  }

  .swiper-box {
    flex: 1;

    .swiper-item {
      height: 100%;
      width: 100%;
    }
  }

  .order-list-card-box {
    .order-card-header {
		flex-wrap: wrap;
      // height: 80rpx;

      .order-no {
        font-size: 26rpx;
        font-weight: 500;
      }

      .order-state {
      }
    }

    .pay-box {
      .discounts-title {
        font-size: 24rpx;
        line-height: normal;
        color: #999999;
      }

      .discounts-money {
        font-size: 24rpx;
        line-height: normal;
        color: #999;
        font-family: OPPOSANS;
      }

      .pay-color {
        color: #333;
      }
    }

    .order-card-footer {
      height: 100rpx;

      .more-item-box {
        padding: 20rpx;

        .more-item {
          height: 60rpx;

          .title {
            font-size: 26rpx;
          }
        }
      }

      .more-btn {
        color: $dark-9;
        font-size: 24rpx;
      }

      .content {
        width: 154rpx;
        color: #333333;
        font-size: 26rpx;
        font-weight: 500;
      }
    }
  }

  :deep(.uni-tooltip-popup) {
    background: var(--ui-BG);
  }
  .warning-color {
    color: #faad14;
  }
  .danger-color {
    color: #ff3000;
  }
  .success-color {
    color: #52c41a;
  }
  .info-color {
    color: #999999;
  }
  .list-item {
    background: #fff;
    border-bottom: 1rpx solid #dfdfdf;
    padding: 30rpx;
  
    .name {
      font-size: 28rpx;
  
      font-weight: 500;
      color: rgba(102, 102, 102, 1);
      line-height: 28rpx;
      margin-bottom: 20rpx;
    }
  
    .time {
      font-size: 24rpx;
  
      font-weight: 500;
      color: rgba(196, 196, 196, 1);
      line-height: 24px;
    }
  
    .add {
      font-size: 30rpx;
  margin-bottom: 20rpx;
      font-weight: 500;
      color: #e6b873;
    }
  
    .minus {
      font-size: 30rpx;
  
      font-weight: 500;
      color: $dark-3;
    }
  }
</style>
